package com.atguigu.chapter07.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/15 14:02
 */
public class Flink05_State_Key_Reduce_2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
            .getExecutionEnvironment()
            .setParallelism(1);
        env
            .socketTextStream("hadoop162", 9999)
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private ReducingState<Integer> sumState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    sumState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>(
                        "sumState",
                        Integer::sum,  // 聚合函数
                        Integer.class
                    ));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    sumState.add(value.getVc());
                    
                    out.collect(ctx.getCurrentKey() + " " + sumState.get());
                }
            })
            .print();
        
        env.execute();
        
    }
}
